#include "xmppcore/stanza.h"
#include "xmppcore/jabberid.h"
#include "xmppcore/xmlwriter.h"
#include "xmppcore/constants.h"
#include "xmppcore/protocoltranslator.h"

namespace yoohoo_xmppcore {

StanzaSharedData::StanzaSharedData() {
	from = 0;
	to = 0;
	obj = 0;
}

StanzaSharedData::StanzaSharedData(const StanzaSharedData& other) : QSharedData(other), from(other.from), to(other.to),
	obj(other.obj), id(other.id), type(other.type), xmlLang(other.xmlLang) {
}

StanzaSharedData::~StanzaSharedData() {
	if (from != 0)
		delete from;

	if (to != 0)
		delete to;

	if (obj != 0)
		delete obj;
}

Stanza::Stanza() {
	_d = new StanzaSharedData;
}

Stanza::Stanza(const Stanza& other) : _d(other._d) {
}

void Stanza::setFrom(const JabberId* from) {
	if (_d->from != 0) {
		delete _d->from;
		_d->from = 0;
	}

	if (from == 0) {
		_d->from = 0;
	} else {
		_d->from = new JabberId(*from);
	}
}

const JabberId* Stanza::from() const {
	return _d->from;
}

void Stanza::setTo(const JabberId* to) {
	if (_d->to != 0) {
		delete _d->to;
		_d->to = 0;
	}

	if (to == 0) {
		_d->to = 0;
	} else {
		_d->to = new JabberId(*to);
	}
}

const JabberId* Stanza::to() const {
	return _d->to;
}

void Stanza::setId(QString id) {
	_d->id = id;
}

QString Stanza::id() const {
	return _d->id;
}

void Stanza::setXmlLang(QString xmlLang) {
	_d->xmlLang = xmlLang;
}

QString Stanza::xmlLang() const {
	return _d->xmlLang;
}

QString Stanza::type() const {
	return _d->type;
}

void Stanza::setObj(XmppObject* obj) {
	if (_d->obj != 0) {
		delete _d->obj;
	}
	_d->obj = obj;
}

XmppObject* Stanza::obj() {
	return _d->obj;
}

XmppElement::ElementType Stanza::elementType() const {
	return XmppElement::ElementTypeStanza;
}

QString	Stanza::toXml() {
	XmlWriter writer;
	
	Stanza::StanzaKind sk = stanzaKind();
	if (sk == Stanza::StanzaKindPresence) {
		writer.writeStartElement(XMPP_STRING_PRESENCE);
	} else if (sk == Stanza::StanzaKindMessage) {
		writer.writeStartElement(XMPP_STRING_MESSAGE);
	} else if (sk == Stanza::StanzaKindIq) {
		writer.writeStartElement(XMPP_STRING_IQ);
	}

	if (!type().isEmpty()) {
		writer.writeAttribute("type", type());
	}

	if (!_d->id.isEmpty()) {
		writer.writeAttribute("id", _d->id);
	}

	if (_d->from != 0) {
		writer.writeAttribute("from", _d->from->toString());
	}

	if (_d->to != 0) {
		writer.writeAttribute("to", _d->to->toString());
	}

	if (!_d->xmlLang.isEmpty()) {
		writer.writeAttribute("xml:lang", _d->xmlLang);
	}

	doToXml(&writer);

	if (_d->obj != 0) {
		ProtocolTranslator* translator = dynamic_cast<ProtocolTranslator*>(_d->obj);
		if (translator != 0) {
			writer.writeCharacters(translator->toXml(), false);
		}
	}
	writer.writeEndElement();

	return writer.toXml();
}

void Stanza::doToXml(XmlWriter* writer) {
}

}
